import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 50000 // request timeout
})

// 请求拦截
service.interceptors.request.use(config => {
    if (store.getters.token) {
      // 请求头添加token
      config.headers['sa-token'] = getToken()
    }
    return config
  },
  error => {
    console.log("请求异常：", error)
    return Promise.reject(error)

  }
)

// 响应拦截
service.interceptors.response.use(response => {

    // 导出
    const headers = response.headers
    if (headers['content-type'] === 'application/octet-stream;charset=utf-8') {
      return response
    }

    // 获取返回信息
    const res = response.data;
    if (res.status === 401) {
      MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }).catch(() => {
      });
      return Promise.reject()
    } else if (res.status === 905) {
      MessageBox.confirm('账号已在其他地方登录，重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }).catch(() => {
      });
      return Promise.reject()
    } else if (res.status === 906) {
      MessageBox.confirm('未登录，请先登录', '系统提示', {
          confirmButtonText: '登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }).catch(() => {
      });
      return Promise.reject()
    } else if (res.status === 500) {
      Message({message: res.msg, type: 'error'})
      return Promise.reject()
    } else if (res.status !== 200) {
      Message({message: res.msg || 'Error', type: 'error',})
      return Promise.reject()
    } else {
      return res
    }
  },
  error => {
    console.log("响应异常：", error.message)
    let {message} = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({message: message, type: 'error', duration: 5 * 1000})
    return Promise.reject(error)
      .catch(e => {
        console.log(e === thenable)
      })
  }
)

export default service
